import axios, {AxiosRequestConfig} from 'axios';
import {message} from 'antd';
import Store from "../redux";
import actions from "../redux/actions";
import JSONbig from 'json-bigint'

import {
    getLocalStorage
} from "../utils";

axios.defaults.withCredentials = true;
const ContentType = 'application/x-www-form-urlencoded;charset=UTF-8';
const timeout = 30 * 1000;
const requestHeader = function (Conf ?: { code: string | number }): AxiosRequestConfig {
    const param: AxiosRequestConfig = {
        timeout,
        withCredentials: true,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            post: {
                'Content-Type': 'application/json',
            },
            token: getLocalStorage('access_token'),
            'Content-Type': Conf['content-type'] || ContentType,
        },
        transformResponse: data => {
            // number长类型精度丢失，number长类型值 默认转 字符串
            return JSON.parse(JSON.stringify(JSONbig.parse(data)));
        }
    };
    if (Conf && Conf.code) {
        param.headers.code = Conf.code; //特殊接口，添加管理员验证
    }
    return param;
};

let _axios;
const toLogin = () => {
    Store.dispatch(actions.clearStore());
    // router.push('/login');
};

function newAxios(Conf) {
    _axios = Conf ? axios.create(requestHeader(Conf)) : axios.create(requestHeader());
    _axios.interceptors.request.use((config) => {
        const state = Store.getState();
        let token = state?.access_token;
        if (token) {
            config.token = token;
        }
        config.headers = {
            ...config.headers,
        };
        return config;
    });
    _axios.interceptors.response.use((response) => {
        // if (notLogin.includes(response.data.code)) {
        //     message.error('===账户已过期===');
        //     toLogin();
        // }
        // 错误消息统一提示
        if (!response.data || (response.data.code && response.data.code !== 200)) {
            message.error(response.data.msg || '请求数据异常，请稍后再试！！');
        }
        if (response.data.code === 708) {
            toLogin();
        }
        return Promise.resolve(response.data || {});
    }, (error) => {
        const originalRequest = error.config;
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1 && !originalRequest._retry) {
            message.error('===请求超时===');
            return Promise.reject({message: '请求超时'});
        }
        let errorText;
        const {response: errResponse} = error;
        const errmessages = {
            400: '===错误请求===',
            401: '===未授权，请重新登录===',
            403: '===拒绝访问===',
            404: '===请求错误,未找到该资源===',
            405: '===请求方法未允许===',
            408: '===请求超时===',
            500: '===服务器端出错===',
            502: '===网络错误===',
            503: '===服务不可用===',
            504: '===网络超时===',
            505: '===http版本不支持该请求===',
            603: '===账户已过期===',
            'else': `===连接错误${errResponse.status || ''}===`,
        };
        if (errResponse) {
            const errorStatus = errResponse?.data?.code || 'else';
            const notLogin = [603, 604, 605, 606, 708]; //需要登录
            errorText = errmessages[errorStatus] || errmessages.else;
            if (notLogin.includes(errorStatus)) {
                toLogin();
                errorText = '登录失效'
            }
        } else {
            errorText = '===网络出现问题，请稍后再试===';
        }
        message.error(errorText);
        return errResponse || {};
    });
}


export const POST = (url, data = {}, config = {}) => {
    newAxios(config);
    return _axios.post(url, data);
};

export const PATCH = (url, data = {}, config = {}) => {
    newAxios(config);
    return _axios.patch(url, data);
};

export const GET = (url, data = {}, config = {}) => {
    newAxios(config);
    return _axios.get(url, {params: data})
};

export const PUT = (url, data = {}, config = {}) => {
    newAxios(config);
    return _axios.put(url, data)
};

export const DELETE = (url, data = {}, config = {}) => {
    newAxios(config);
    return _axios.delete(url, {data})
};
